import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class L199_2 {
    class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<>();
            if (root == null) {
                return result;
            }
            LinkedList<TreeNode> nodes = new LinkedList<>();
            nodes.offer(root);
            while (!nodes.isEmpty()) {
                int size = nodes.size();
                int view = 0;
                while (size > 0) {
                    TreeNode node = nodes.poll();
                    if (node.left != null) {
                        nodes.offer(node.left);
                    }
                    if (node.right != null) {
                        nodes.offer(node.right);
                    }
                    view = node.val;
                    size--;
                }
                result.add(view);
            }
            return result;
        }
    }
}
